package com.yn.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName: Producer
 * @Description: 简单模式：生产者
 * @author: 王胜
 * @date 2021/3/31
 * @Version: 1.0
 **/
public class Producer {
    public static void main(String[] args)  {
        //amqp协议基于tcp/ip协议
        //ip,port
        //创建连接工厂
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        Connection connection=null;
        Channel channel =null;
//        获取连接
        try {
            connection= factory.newConnection("生产者");
            //通过连接获取通道
            channel=connection.createChannel();
            //通过通道创建交换机，声明队列，路由key，绑定，发送消息，接收消息
            String queue1="queue1";
            channel.queueDeclare(queue1,true,false,false,null);
            //准备消息
            String message="你好，你在吗";
            //发送消息给队列
            channel.basicPublish("",queue1,null,message.getBytes());
            System.out.println("send successfully");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {
            //关闭连接
            if(connection!=null&&connection.isOpen()){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭通道
            if(channel!=null&&channel.isOpen()){
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
